# -*- coding:utf-8 -*-
"""
Web服务器运行脚本
"""
from __future__ import print_function, unicode_literals
from functools import wraps
from flask import request, Flask
from json import dumps, loads

import traceback
from flask_utility.config import UrlError, ArgLackError, ArgExceptionError, RetDict, RetDirect, RetDictData


class RestApiProcess(object):
    """
    对输入参数和输出参数进行处理
    """
    def __init__(self, logger, ret_fun=RetDict(), ensure_ascii=True):
        self.logger = logger
        self.ret_fun = ret_fun
        self.ensure_ascii = ensure_ascii

    def wrap(self, fun):
        @wraps(fun)
        def wrap_(*args, **kwargs):
            try:
                if request.method == 'POST':
                    in_data = request.json
                    if not in_data:
                        in_data = request.form
                    if not in_data:
                        in_data = loads(request.get_data())
                else:
                    in_data = request.args
                self.logger.debug(
                    "request[%s]: %s",
                    request.method,
                    in_data)

                data = fun(in_data, *args, **kwargs)
                result = self.ret_fun.success(data)

            except UrlError as _:
                result = self.ret_fun.urlerror()

            except ArgLackError as _:
                result = self.ret_fun.arglack()

            except ArgExceptionError as _:
                result = self.ret_fun.arglogic()

            except Exception as e:
                self.logger.exception(e)
                result = self.ret_fun.exception(str(e))

            self.logger.debug(
                'response data status(%s) keys(%s)',
                self.ret_fun.code(result),
                self.ret_fun.msg(result))
            if self.ensure_ascii:
                return dumps(result)
            else:
                return dumps(result, ensure_ascii=False, indent=4)

        return wrap_

    def wrap_with_html(self, fun):
        @wraps(fun)
        def wrap_(*args, **kwargs):
            try:
                if request.method == 'POST':
                    in_data = request.json
                    if not in_data:
                        in_data = request.form
                    if not in_data:
                        in_data = loads(request.get_data())
                else:
                    in_data = request.args
                self.logger.debug(
                    "request[%s]: %s",
                    request.method,
                    in_data)

                data = fun(in_data, *args, **kwargs)
                result = self.ret_fun.success(data)

            except UrlError as _:
                result = self.ret_fun.urlerror()

            except ArgLackError as _:
                result = self.ret_fun.arglack()

            except ArgExceptionError as _:
                result = self.ret_fun.arglogic()

            except Exception as e:
                self.logger.warning(e)
                traceback.print_exc()
                result = self.ret_fun.exception(str(e))

            self.logger.debug(
                'response data status(%s) keys(%s)',
                self.ret_fun.code(result),
                self.ret_fun.msg(result))

            if in_data.get('html'):
                str_ = dumps(result, ensure_ascii=False, indent=4)
                str_ = str_.replace('\n', '<br/>').replace(' ', '&nbsp;')
                return '<html><p>' + str_ + '</p></html>'
            else:
                return dumps(result)

        return wrap_


if __name__ == '__main__':
    from logger_utility.loggconfig import getLogger
    app = Flask(__name__)
    logger = getLogger('Server')
    rest_api_process = RestApiProcess(logger, ensure_ascii=False)


    @app.route('/echo', methods=['POST', 'GET'])
    @rest_api_process.wrap_with_html
    def process(in_data):
        """
        实际查找敏感词的函数
        :param in_data: 
        :return: 
        """
        ret = in_data
        return ret

    app.run(debug=False, host='0.0.0.0', port=10099, threaded=True)
